from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from fake_useragent import UserAgent
class Browser(object):
    def createItem(self):
        maxTimeout = 60
        chromeOptions = webdriver.ChromeOptions()
        # chromeOptions.add_argument("--headless")
        # chromeOptions.add_argument("--disable-gpu")
        chromeOptions.add_argument("--mute-audio")
        chromeOptions.add_argument('--disable-dev-shm-usage')
        chromeOptions.add_argument('--no-sandbox')
        chromeOptions.add_experimental_option("excludeSwitches", ["enable-automation"])
        chromeOptions.add_experimental_option("useAutomationExtension", False)
        chromeOptions.add_argument('--disable-web-security')
        chromeOptions.add_argument("--blink-settings=imagesEnabled=false")
        chromeOptions.add_argument('--ignore-certificate-errors')
        chromeOptions.add_argument('--ignore-ssl-errors')
        chromeOptions.add_argument('--ignore-ssl-error')
        chromeOptions.add_argument('--ignore-certificate-errors-spki-list')
        # chromeOptions.add_argument('--proxy-server=http://a901.kdltps.com:15818')
        chromeOptions.add_argument('--user-agent={}'.format(UserAgent().random))
        browser = webdriver.Chrome(options=chromeOptions)
        browser.set_window_size(1920, 1080)
        browser.set_page_load_timeout(maxTimeout)
        browser.implicitly_wait(10)
        browser.execute_cdp_cmd(
            "Page.addScriptToEvaluateOnNewDocument",
            {
                "source": """
                Object.defineProperty(navigator, 'webdriver', {
                get: () => undefined
                })
                """
            },
        )
        return browser
    
    def restartItem(self):
        self.item.quit()
        self.item = self.createItem()

    
    def stopItem(self):
        self.item.quit()

    def startItem(self):
        self.item = self.createItem()

    def __init__(self):
        self.item = self.createItem()